package com.ruoyi.device.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.RedisConstans;
import com.ruoyi.common.core.domain.HatDeviceLog;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.device.domain.HatDevice;
import com.ruoyi.device.domain.req.hatdevice.HatDeviceAddReq;
import com.ruoyi.device.domain.req.hatdevice.HatDeviceEditReq;
import com.ruoyi.device.domain.req.hatdevice.HatDeviceReq;
import com.ruoyi.device.domain.resp.hatdevice.HatDeviceByIdResp;
import com.ruoyi.device.domain.resp.hatdevice.HatDeviceResp;
import com.ruoyi.device.domain.resp.hatdevice.HatDeviceSearchResp;
import com.ruoyi.device.service.HatDeviceService;
import com.ruoyi.device.mapper.HatDeviceMapper;
import com.ruoyi.device.util.UpdateRedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author 11452
* @description 针对表【hat_device】的数据库操作Service实现
* @createDate 2023-11-24 17:14:58
*/
@Service
public class HatDeviceServiceImpl extends ServiceImpl<HatDeviceMapper, HatDevice>
    implements HatDeviceService{

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UpdateRedisUtils updateRedisUtils;

    @Override
    public List<HatDeviceResp> searchByOrgCode(String orgCode) {
        //        LambdaQueryWrapper<HatDevice>  queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(HatDevice::getSysOrgCode,orgCode);
//        queryWrapper.eq(HatDevice::getDelFlat,"0");
//        List<HatDevice> deviceList = super.list(queryWrapper);
        List<HatDeviceResp> deviceList= this.baseMapper.searchDeviceByOrgCode(orgCode);

        //得到所有的设备ID
        List<String> collect = deviceList.stream().map(HatDeviceResp::getDeviceCode).collect(Collectors.toList());

        //查询redis日志
        List<HatDeviceLog> redisDeviceLog = this.redisTemplate.opsForHash().multiGet(RedisConstans.HAT_DEVICE_HASH_KEY, collect);

        //组装
        for(HatDeviceResp db: deviceList){

            //设备正常，判断是否离线了
            if(db.getStatus().equals("1")){

               //判断有收到消息没有
                List<HatDeviceLog> collect1 = redisDeviceLog.stream().filter(p -> p.getDeviceId().equals(db.getDeviceId())).collect(Collectors.toList());
                //有消息
                if(!collect1.isEmpty()){
                    HatDeviceLog hatDeviceLog = collect1.get(0);
                    db.setUpdateTime(hatDeviceLog.getCreateTime());
                    //消息时间是30秒之前的数据
                    if(System.currentTimeMillis()- hatDeviceLog.getCreateTime().getTime() >30*1000L){
                        db.setRealTimeState("离线");
                    }else {
                        //正常，设备经纬度
                        db.setLat(hatDeviceLog.getLat());
                        db.setLon(hatDeviceLog.getLon());
                        db.setRealTimeState("正常");
                    }
                }else{
                    db.setRealTimeState("离线");
                    db.setUpdateTime(new Date());
                }
            }else{
                db.setStatus(db.getStatus());
            }

        }

        return deviceList;
    }

    /**
     * 分页查询安全帽视图
     * @param req
     * @return
     */
    @Override
    public List<HatDeviceSearchResp> search(HatDeviceReq req) {
        return this.baseMapper.search(req);
    }

    /**
     * 新增安全帽
     * @param req
     * @return
     */
    @Override
    public Boolean add(HatDeviceAddReq req) {
        LambdaQueryWrapper<HatDevice> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(HatDevice::getDeviceCode,req.getDeviceCode());
        HatDevice hatDevice = this.getOne(queryWrapper);

        if(!Objects.isNull(hatDevice)){
            throw new ServiceException("安全帽编码已经存在");
        }
        hatDevice=new HatDevice();
        //根据地区名称来查询编号  存入实体
        if(!StrUtil.isBlank(req.getSysOrgName())){

            SysDictData dictData = this.baseMapper.findByDictDataLabel(req.getSysOrgName());
            if(Objects.isNull(dictData)){
                throw new ServiceException("找不到该地区");
            }
            String dictValue = dictData.getDictValue();
            hatDevice.setSysOrgCode(dictValue);
        }
        hatDevice.setCreateBy(req.getCreateBy());
        hatDevice.setDelFlat("0");
        hatDevice.setCreateTime(new Date());
        hatDevice.setStatus(req.getStatus());
        hatDevice.setDeviceCode(req.getDeviceCode());

        boolean save = this.save(hatDevice);

        return save;
    }

    @Override
    public Boolean edit(HatDeviceEditReq req) {
        LambdaQueryWrapper<HatDevice> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(HatDevice::getDeviceId,req.getDeviceId());
        HatDevice hatDevice = this.getOne(queryWrapper);

        if(Objects.isNull(hatDevice)){
            throw new ServiceException("设备不存在");
        }

        String sysOrgCode = this.baseMapper.findByDictDataLabel(req.getSysOrgName()).getDictValue();
        if(sysOrgCode==null){
            throw new ServiceException("找不到该地区");
        }

        HatDevice updateHat = new HatDevice();

        BeanUtils.copyProperties(req,updateHat);
        updateHat.setSysOrgCode(sysOrgCode);
        updateHat.setDelFlat("0");
        updateHat.setUpdateBy(req.getUpdateBy());
        updateHat.setUpdateTime(new Date());
        boolean update = this.updateById(updateHat);

        return update;
    }

    @Override
    public HatDeviceByIdResp findByid(Long id) {
        HatDevice byId = this.getById(id);
        if(Objects.isNull(byId)){
            throw new ServiceException("找不到设备");
        }

        HatDeviceByIdResp hatDeviceByIdResp = new HatDeviceByIdResp();

        SysDictData dictDataByValue = this.baseMapper.findDictDataByValue(byId.getSysOrgCode());

        hatDeviceByIdResp.setDeviceId(byId.getDeviceId());
        hatDeviceByIdResp.setDeviceCode(byId.getDeviceCode());
        hatDeviceByIdResp.setSysOrgName(dictDataByValue.getDictLabel());
        hatDeviceByIdResp.setStatus(byId.getStatus());

        return hatDeviceByIdResp;
    }

    @Override
    public boolean updateDel(Long[] ids) {

        for (Long id : ids) {
            HatDevice db = this.getById(id);

            if(Objects.isNull(db)){
                throw new ServiceException("找不到数据");
            }
            db.setDelFlat("1");
            //更新已经绑定的设备
            this.updateRedisUtils.updateBingDevice();
            this.updateById(db);
        }

        return true;
    }

    /**
     * 查询没有绑定的设备
     * @return
     */
    @Override
    public List<HatDeviceResp> searchUnBind() {
        List<HatDeviceResp> hatDeviceResps = this.baseMapper.searchUnBind();
        return hatDeviceResps;
    }
}




